package com.dongdongshop.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.PageUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.dk.util.PageResult;
import com.dongdongshop.mapper.TbOrderItemMapper;
import com.dongdongshop.mapper.TbOrderMapper;
import com.dongdongshop.pojo.*;
import com.dongdongshop.service.TbAddressService;
import com.dongdongshop.service.Tborderservice;
import com.dongdongshop.util.IdWorker;
import com.dongdongshop.vo.AddressVo;
import com.dongdongshop.vo.CartVO;
import com.dongdongshop.vo.payVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.rocketmq.client.producer.TransactionSendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

@Service
@DubboService
public class Tborderserviceimpl  implements Tborderservice {


    @Autowired
    TbOrderMapper tom;//购物车商家

    @Autowired
    TbOrderItemMapper tim;//购物车详细表

    @DubboReference
    TbAddressService ts;//地址信息

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    RocketMQTemplate rocketMQTemplate;


    @Autowired
    private MongoTemplate mongoTemplate;



    @Transactional
    @Override
    public Map<String ,Object>  addorder(Long userid, String strs, Long id) {
        System.out.println(id);
        AddressVo uservo= ts.getaddVoid(userid);//用户信息

        List<CartVO> cartlist = (List<CartVO>) redisTemplate.boundHashOps("cartlist").get(id);
        Map<String ,Object> map=new HashMap<>();
        double moneys=0;//全部总价格
        String name="";//商品描述
        List<Long> ls=new ArrayList<>();//获取订单集合

        for (CartVO cart:cartlist) {
            IdWorker idWorker=new IdWorker();
            long l = idWorker.nextId();//主键,订单id
            TbOrder tod=new TbOrder();//新创建订单表
            tod.setOrderId(l);//订单id
            ls.add(l);
            tod.setUserId(uservo.getUsername());//用户名
            tod.setPaymentType(strs);
            tod.setStatus("1");
            tod.setReceiverAreaName(uservo.getAddress());
            tod.setReceiverMobile(uservo.getMobile());//手机号
            tod.setReceiver(uservo.getContact());//收货人
            tod.setSellerId(cart.getSellerid());//商家id
            tod.setCreateTime(new Date());//创建时间
            //循环购物车明细
            double money=0;
            for(TbOrderItem orderItem:cart.getList()){

                orderItem.setId(idWorker.nextId());//主键
                orderItem.setOrderId(l);//订单id
                orderItem.setSellerId(cart.getSellerid());
                money+=orderItem.getTotalFee().doubleValue();//商品金额
                tim.insert(orderItem);//增加方法
                moneys+=money;
                name+=orderItem.getTitle();//商品描述
            }
            tod.setPayment(new BigDecimal(money));//购物车总表价格
            tom.insert(tod);//增加方法
        }

        redisTemplate.boundHashOps("cartlist").delete(id);

        IdWorker iw=new IdWorker();
        map.put("id",iw.nextId());//订单号
        map.put("price",moneys);
        map.put("name",name);
        map.put("names",name);

        String key="dingdan";
        redisTemplate.delete(key);
        for(int i=0;i<ls.size();i++){
            String s = JSONObject.toJSONString(ls.get(i));
            redisTemplate.boundSetOps(key).add(s);
        }
        return map;
    }




    //修改订单状态
    //修改为已支付
    @Override
    public int updateStatus(List<Long> ls) {
        String s="2";//已付款
        List<TbOrder> tbls=new ArrayList<>();
        for(int i=0;i<ls.size();i++){
            TbOrder tbOrder = tom.selectByPrimaryKey(ls.get(i));
            tbOrder.setStatus(s);
            tbls.add(tbOrder);
        }
        for( int i=0;i<tbls.size();i++){
            tom.updateByPrimaryKey(tbls.get(i));
        }
        return 1;
    }


    //主键查询
    @Override
    public List<TbOrder> getall(List<Long> ls) {
        List<TbOrder> tdls=new ArrayList<>();
        for(int i=0;i<ls.size();i++){
           tdls.add(tom.selectByPrimaryKey(ls.get(i)));
        }
        return tdls;
    }


    //查询订单成功的
    @Override
    public List<TbOrder> getallSend() {
        String s="2";//已付款
        return tom.getallSend(s);
    }


    //查询已支付的全部
    @Override
    public PageResult getStauts(Integer pagenum, Integer pagesize,String date1,String date2) {
        DateTime parse1 = DateUtil.parse(date1);//字符串转日期类型
        DateTime parse2 = DateUtil.parse(date2);
        PageHelper.startPage(pagenum,pagesize);
        String s="2";//已付款
        List<TbOrder> ls = tom.getstaut(s,parse1,parse2);
        PageInfo info=new PageInfo(ls);
        PageResult p=new PageResult(pagenum,pagesize,info.getList(),info.getTotal());
        return p;
    }

    //查询日期范围
    @Override
    public List<TbOrder> getDate(String date1, String  date2) {
        DateTime parse1 = DateUtil.parse(date1);//字符串转日期类型
        DateTime parse2 = DateUtil.parse(date2);
        String stauts="2";//已付款
        List<TbOrder> ls = tom.getDate(parse1, parse2, stauts);
        return  ls;
    }


    //设置交易订单号与交易流水号
    //商户订单号,支付宝交易流水号
    @Override
    public int setorder(String out_trade_no, String trade_no, List<Long> ls) {
        List<TbOrder> tbls=new ArrayList<>();
        for(int i=0;i<ls.size();i++){
            TbOrder tbOrder = tom.selectByPrimaryKey(ls.get(i));
            tbOrder.setPostFee(out_trade_no);
            tbOrder.setShippingCode(trade_no);
            tbls.add(tbOrder);
        }
        for( int i=0;i<tbls.size();i++){
            tom.updateByPrimaryKeySelective(tbls.get(i));
        }
        return 1;
    }



    //退款修改订单状态
    @Override
    public int upstauts(Long order) {
        String s="8";
        TbOrder tbOrder = tom.selectByPrimaryKey(order);
        tbOrder.setStatus(s);
        return tom.updateByPrimaryKeySelective(tbOrder);
    }



    // 分布式事务
    // 添加积分

    /**
     *
     * @param orderId  主键id
     * @param trade_no 支付宝流水号
     * @param out_trade_no 订单号
     * @param status 状态
     * @return
     * 以上参数修改订单状态用
     */
    @Override
    public String updateOrderStatus(Long orderId, String trade_no, String out_trade_no, String status, String userid, double money) {
        //先发送办消息
        //将发送的半消息转换为json
        JsonObject json=new JsonObject();
        json.addProperty("userId",userid);
        json.addProperty("money",money);
        String jsonstr = json.toString();//此处封装的是消费者积分要用的数据
        Message<String> message = MessageBuilder.withPayload(jsonstr).build();

        //将要修改的订单数据封装到order实体类中
        TbOrder order=new TbOrder();
        order.setShippingCode(trade_no);//交易流水号
        order.setOrderId(orderId);
        order.setPostFee(out_trade_no);//交易订单号
        order.setStatus(status);
        //发送半消息
        TransactionSendResult result = rocketMQTemplate.sendMessageInTransaction("tx-topic", message, order);
        System.out.println(JSONUtil.toJsonStr(result));
        return "ok";
    }



    //查询订单号与流水号
    @Override
    public List<TbOrder> byorder(String out_trade_no) {
        return tom.byorder(out_trade_no);
    }



//    //查询评论
    @Override
    public List<common>  selectComment() {
        Query query = new Query();
        List<common> commons = mongoTemplate.find(query, common.class);
        return commons;
    }





    //增加评论
    @Override
    public int insertComment(common com) {
        mongoTemplate.insert(com);
        return 1;
    }













}
